package com.alipay.service.job;


import com.alipay.constants.Constants;
import com.alipay.mapper.RedBagTransMapper;
import com.alipay.model.dto.TransDto;
import com.alipay.model.entity.RedBagTransEntity;
import com.alipay.model.enums.TransStatusEnum;
import com.alipay.service.rpc.TransService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 对红包明细表中转账失败的记录重新进行处理
 *
 * @author Jun
 */
@Slf4j
@Service
public class TransferTaskDealJob {

    @Resource
    private RedBagTransMapper redBagTransMapper;

    @Autowired
    private TransService transService;

    @Scheduled(cron = "0 */1 * * * ?")
    public void processJob() {
        // 每1分钟执行一次，获取1分钟之前未达到最终态的任务, 具体时间间隔可以根据业务具体调整
        RedBagTransEntity query = new RedBagTransEntity();
        query.setStatus(TransStatusEnum.FAIL.getStatus());

        // 每次处理一部分，不需要全部加载进内存
        List<RedBagTransEntity> transTaskEntities = redBagTransMapper.queryRedBagTransInfo(query, Constants.LIMIT);
        if (CollectionUtils.isEmpty(transTaskEntities)) {
            return;
        }
        while (CollectionUtils.isNotEmpty(transTaskEntities)) {

            transTaskEntities.parallelStream().forEach(transTaskEntity ->
                    transService.trans(new TransDto(transTaskEntity.getRedBagNo(), transTaskEntity.getUserId()))
            );

            // 再取下一部分数据
            transTaskEntities = redBagTransMapper.queryRedBagTransInfo(query,
                    transTaskEntities.get(transTaskEntities.size() - 1).getId(), Constants.LIMIT);
        }
    }
}
